<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;

require_once __DIR__ . '/vendor/autoload.php';

$global_uid = 0;

// 创建一个 Worker 监听 9501 端口，使用 text 协议
$worker = new Worker("text://0.0.0.0:9501");

$worker->count = 1;
Worker::$stdoutFile = 'stdout.log';

$worker->onConnect = function(TcpConnection $connection) {
    global $global_uid;
    $connection->uid = ++$global_uid;
};

$worker->onMessage = function(TcpConnection $connection, $data) {
    global $worker;
    foreach ($worker->connections as $conn) {
        $conn->send("user[$connection->uid] said: $data");
    }
};

$worker->onClose = function(TcpConnection $connection) {
    global $worker;
    foreach ($worker->connections as $conn) {
        $conn->send("user[$connection->uid] logout");
    }
};

$worker->onWorkerStart = function(Worker $worker) {
    echo "Worker started: $worker->id\n";
};

$socketName = $worker->getSocketName();
echo "Worker started: $socketName\n";

Worker::runAll();
